import { Context, h, Schema } from 'koishi'

export const name = 'get-avatar'

export interface Config {}

export const Config: Schema<Config> = Schema.object({})

export const usage = `get_avatar [at_user]\n\n`;

export function apply(ctx: Context) {
  // write your plugin here
  ctx.command("get_avatar")
    .action( async ({session, options}) => {
      let uid;
      let UID_SOURCE;

      let at_user = null;
      for ( const e of session.event.message.elements ){
        if ( e.type === "at" ){
          at_user = e; break;
        }
      }

      if ( at_user !== null ){
        UID_SOURCE = "AT";
        uid = at_user.attrs.id;
      } else {
        UID_SOURCE = "SELF";
        uid = session.userId;
      }

      let msg = ``;
      msg += `[debug]UID_SOURCE: ${UID_SOURCE}\n`;
      msg += `[debug]uid: ${uid}\n`;
      await ctx.logger.info(msg);

      try{

        let msg = [];
        const user = await session.bot.getUser(uid);
        const userAvatarUrl = user.avatar;
        msg.push(`[debug]Url of user: ${userAvatarUrl}\n`);
        msg.push(`\t↓ Avatar of user ↓\n`);
        msg.push(h.image(userAvatarUrl));
        await session.send(msg);

      } catch (err) {

        let errMsg = `[error]Failed when getting avatar: ${err}`;
        await session.send(errMsg);
        await ctx.logger.error(errMsg);

      }
    })
}
